package com.google.code.mochaccino.framework.ui.services;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.code.mochaccino.framework.ui.services.form.FormSubmitError;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * The Console Service Result is an object encapsulating the concept of success/failure
 * for a ui-service.
 */
public class ServiceResult {

	/** The Form Errors */
	private List<FormSubmitError> formErrors = new ArrayList<FormSubmitError>();

	/** The Service Global Error Message (Pre-Localized) */
	private String errorMessage;

	/** The Success or Failure Status. */
	private boolean success;

	/** Constructor */
	private ServiceResult( boolean success, String errorMessage ) {
		this.success = success;
		this.errorMessage = errorMessage;
	}

	/** Fail */
	public static final ServiceResult fail( String msg, FormSubmitError... errors ) {
		Preconditions.checkNotNull( msg, "Message cannot be null!" );
		Preconditions.checkArgument( msg.trim().length() != 0, "Message cannot be empty!" );
		ServiceResult result = new ServiceResult( false, msg );
		result.add( errors );
		return result;
	}

	/** Add errors */
	private void add( FormSubmitError... errors ) {
		if ( errors != null ) {
			for ( FormSubmitError error : errors ) {
				formErrors.add( error );
			}
		}
	}

	/** Success */
	public static final ServiceResult success() {
		return new ServiceResult( true, "" );
	}

	/** Return the Error Message */
	public String getErrorMessage() {
		return errorMessage;
	}

	/** Get Form Errors */
	public Collection<FormSubmitError> getFormErrors() {
		return new ArrayList<FormSubmitError>( formErrors );
	}

	/** Is Success? */
	public boolean isSuccess() {
		return success;
	}
}
